package xupt.com.bolg.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.stereotype.Service;
import xupt.com.bolg.entity.Reward;
import xupt.com.bolg.repository.RewardRepository;
import xupt.com.bolg.service.RewardService;

import java.util.ArrayList;
import java.util.List;


@Service
public class RewardServiceImpl implements RewardService {
    @Autowired
    RewardRepository rewardRepository;

    @Override
    public boolean saveReward(Integer userId, Integer pace,Integer meId) {
        Reward reward = findByUserId(userId);
        Reward me = findByUserId(meId);
        if(me.getPace()<pace){
            return false;
        }
        me.setPace(me.getPace()-pace);
        rewardRepository.save(me);


        if(reward==null){   //没有这个表第一次打赏
            reward.setPace(pace+100);
            reward.setUserId(userId);
            rewardRepository.save(reward);
            return true;
        }else {
            //打赏     直接加上原有的值
            reward.setPace(pace+reward.getPace());
            rewardRepository.save(reward);
            return true;
        }
    }

    @Override
    public Integer changeMoney(Integer userID) {
        Reward reward = findByUserId(userID);
        if(reward!=null){
           Integer money= reward.getPace()%100;
           reward.setPace(reward.getPace()-money*100);
           rewardRepository.save(reward);
           return money;
        }
        return 0;
    }
    @Override
    public Reward findByUserId(Integer userID) {
        //没有就创建一个
        //设置匹配器,匹配规则
        ExampleMatcher matcher=ExampleMatcher.matching()
                .withIgnorePaths("id","pace");
        Reward reward=new Reward();
        reward.setUserId(userID);
        Example example=Example.of(reward,matcher);
        ArrayList<Reward> all = (ArrayList<Reward>) rewardRepository.findAll(example);
        //按理应该查出来的是一个
        if(all==null){
            Reward reward1=new Reward(userID,100);
            int ID=all.get(all.size()-1).getId()+1;
            reward1.setId(ID);
            rewardRepository.save(reward1);
            return reward1;
        }else {
            Reward reward1 = all.get(0);
            return reward1;
        }
    }

    @Override
    public boolean adddodo(Integer userID,  Integer pace) {
        Reward reward = findByUserId(userID);
        reward.setPace(reward.getPace()+pace);
        rewardRepository.save(reward);
        return true;
    }
}
